
cd $firmpath 

global firstyear 1996 
global lastyear 2010


use $correspath/corres_nc8$firstyear$lastyear.dta, clear // 19952010.dta, clear 
cap g nc8 = cn8
egen _=count(nc8), by(id_conc year) 
sort id_conc year
bys id_conc: egen nbm=max(_)
keep if year==2002 
tostring nc8, replace 
replace nc8="0"+nc8 if length(nc8)==7
g hs6_2002 =substr(nc8,1,6) if length(nc8)==8  

keep hs6 id_conc 
*destring hs6, replace
merge m:1 hs6_2002 using $rspath/tmp_rs
keep if _m==3 
collapse (mean) rsbs* , by(id_conc)
save temp, replace 


clear 
g iter=0 
save table_decompo_bs, replace

forvalue i=1(1)400 {
	

use decompo_margin_$firstyear$lastyear, clear 
merge m:1 id_conc using temp , keepusing(rsbs`i') keep(match)
keep rsbs`i' uncertainty crisis g_all entri exitc intens p
g eta_uncert=uncertainty*rsbs`i'
g eta_crisis=crisis*rsbs`i'
rename rsbs`i' eta 

	foreach y in g_all entri exitc intens{ 
		reg `y' uncertainty crisis eta_uncert eta_crisis eta
			foreach j in eta eta_uncert uncertainty crisis eta_crisis{
			g coef_`y'`j'=_b[`j']
			}
	}
	keep coef* 
	g iter=`i' 
	keep if _n==1 
	append using table_decompo_bs
	save table_decompo_bs, replace
	dis `i'
}


use table_decompo_bs, clear
	foreach i in coef_g_alleta coef_g_alleta_uncert coef_g_alluncertainty coef_g_allcrisis coef_g_alleta_crisis coef_entrieta coef_entrieta_uncert coef_entriuncertainty coef_entricrisis coef_entrieta_crisis coef_exitceta coef_exitceta_uncert coef_exitcuncertainty coef_exitccrisis coef_exitceta_crisis coef_intenseta coef_intenseta_uncert coef_intensuncertainty coef_intenscrisis coef_intenseta_crisis {
	egen sd_`i'=sd(`i')
    egen m_`i'=mean(`i')
	}

	keep sd_coef_* m_coef_*
	
collapse (mean) sd_* m_* 
g one=1 
reshape long m_coef_g_all sd_coef_g_all m_coef_entri sd_coef_entri  m_coef_exitc sd_coef_exitc  m_coef_intens sd_coef_intens 	, i(one) j(variable) s


foreach y in g_all entri exitc intens{ 
rename m_coef_`y' `y'm
rename sd_coef_`y' `y'sd
}

reshape long g_all entri exitc intens, i(one variable) j(type)s
drop one
save $outputpath/table_OA11, replace 

erase temp.dta
